package com.zut.yunxi.yunxi.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ClientDetailsService clientDetailsService;
      @Autowired
       private  AuthorizationCodeServices authorizationCodeServices;
      @Autowired
      private AuthenticationManager authenticationManager ;
      @Autowired
      private JwtAccessTokenConverter accessTokenConverter;
        @Autowired
        private PasswordEncoder passwordEncoder;


      @Bean
      public ClientDetailsService clientDetailsService(DataSource dataSource)
      {

            ClientDetailsService clientDetailsService=new JdbcClientDetailsService(dataSource);
          ((JdbcClientDetailsService)clientDetailsService).setPasswordEncoder(passwordEncoder);
          return clientDetailsService;
      }
    /**
     * 配置客户端详情
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
       /* clients.inMemory().withClient("c1").secret(new BCryptPasswordEncoder().encode("secret"))
                .resourceIds("res1").authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token").scopes("all").autoApprove(false)
                .redirectUris("http://www.baidu.com");*/
    }
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices services=new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);//客户详情
        services.setSupportRefreshToken(true);//支持刷新
        services.setTokenStore(tokenStore);
        services.setAccessTokenValiditySeconds(7200);//默认令牌2小时
        services.setRefreshTokenValiditySeconds(259200);
        TokenEnhancerChain tokenEnhancerChain=new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        services.setTokenEnhancer(tokenEnhancerChain);
        return services;
    }
    //设置授权码，暂时用内存
   /* @Bean
    public AuthorizationCodeServices authorizationCodeServices()
    {

        return new InMemoryAuthorizationCodeServices();
    }*/
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource)
    {

        return new JdbcAuthorizationCodeServices(dataSource);
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer configurer)
    {
        configurer.authenticationManager(authenticationManager)//认证管理器
                .authorizationCodeServices(authorizationCodeServices)//授权码服务
                .tokenServices(tokenServices())//令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET,HttpMethod.OPTIONS);
    }

    /**
     * 服务器端点配置
     * @param securityConfigurer
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer securityConfigurer)
    {
        securityConfigurer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")

                .allowFormAuthenticationForClients();
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("linux"));
    }

}
